﻿namespace ImageServer.Util;

using System;
using System.Security.Cryptography;
using System.Text;

public static class PasswordHasher
{
    /// <summary>
    /// 计算字符串的哈希值
    /// </summary>
    /// <param name="input">输入字符串</param>
    /// <param name="algorithm">哈希算法，如 SHA256、SHA1、MD5</param>
    /// <returns>哈希值</returns>
    public static string CalculateHash(string input, string algorithm)
    {
        // 将输入字符串转换为字节数组
        byte[] inputBytes = Encoding.UTF8.GetBytes(input);

        // 根据指定的算法创建哈希实例
        using (HashAlgorithm hashAlgorithm = HashAlgorithm.Create(algorithm))
        {
            if (hashAlgorithm == null)
            {
                throw new ArgumentException("不支持的哈希算法: " + algorithm);
            }

            // 计算哈希值
            byte[] hashBytes = hashAlgorithm.ComputeHash(inputBytes);

            // 将字节数组转换为十六进制字符串
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString("x2")); // "x2" 表示以小写十六进制格式输出
            }

            return sb.ToString();
        }
    }

    /// <summary>
    /// 计算字符串的SHA-256哈希值
    /// </summary>
    /// <param name="input">输入字符串</param>
    /// <returns>SHA-256哈希值</returns>
    public static string CalculateSHA256(string input)
    {
        return CalculateHash(input, "SHA256");
    }

    /// <summary>
    /// 计算字符串的SHA-1哈希值
    /// </summary>
    /// <param name="input">输入字符串</param>
    /// <returns>SHA-1哈希值</returns>
    public static string CalculateSHA1(string input)
    {
        return CalculateHash(input, "SHA1");
    }

    /// <summary>
    /// 计算字符串的MD5哈希值
    /// </summary>
    /// <param name="input">输入字符串</param>
    /// <returns>MD5哈希值</returns>
    public static string CalculateMD5(string input)
    {
        return CalculateHash(input, "MD5");
    }
}